package com.example.crawler.youtube;


import com.example.crawler.youtube.exception.YoutubeException;
import com.example.crawler.youtube.model.ConvertResult;
import com.example.crawler.youtube.model.YoutubeExtractorResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

/**
 * @author fcxx1
 */
@Component
public class YoutubeExtractorManager {
    private static Logger logger = LoggerFactory.getLogger(YoutubeExtractorManager.class);
    private final List<Extractor> extractorList;

    @Autowired
    public YoutubeExtractorManager(List<Extractor> extractorList) {
        this.extractorList = extractorList;
    }

    public ConvertResult<YoutubeExtractorResult> convertYoutubeVideo(String ytUrl) throws YoutubeException {
        Iterator<Extractor> it = extractorList.iterator();
        while (it.hasNext()) {
            Extractor extractor = it.next();
            if (extractor.enable()) {
                long startTime = System.currentTimeMillis();
                logger.info("[start to extract youtube video, extractor is {}]", extractor.name());
                try {
                    final ConvertResult<YoutubeExtractorResult> convertResult = extractor.convert(ytUrl);
                    long duration = (System.currentTimeMillis() - startTime) / 1000;
                    logger.info("[end to extract youtube video, duration second is {}, result is {}]", duration, convertResult.isSuccess());
                    if (convertResult.isSuccess()) {
                        convertResult.setConverter(extractor.name());
                        return convertResult;
                    }
                } catch (Exception e) {
                    logger.error("[{}]转换发生异常", extractor.name(), e);
                    // 当最后一个提取者抛出异常时，提取任务终止，向上抛出异常
                    if (!it.hasNext()) {
                        ConvertResult<YoutubeExtractorResult> result = ConvertResult.failure();
                        result.setError(e.getMessage());
                        return result;
                    }
                }
            }
        }
        throw new YoutubeException(ytUrl, "未解析到对应的URL");
    }
}
